package vn.bang.xiangqi.server;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Collection;
import java.util.Map;
import java.util.Queue;

import vn.bang.communication.Command;
import vn.bang.communication.Communicator;
import vn.bang.entity.GameDTO;
import vn.bang.entity.PlayerDTO;
import vn.bang.xiangqi.server.log.Log;

public class XiangqiServer extends AbstractBaseServer {

	public XiangqiServer(Queue<Command> commandQueue, Map<Long, Communicator> communicators, Collection<PlayerDTO> players, Collection<GameDTO> games, int numberOfThreads) {
		super(commandQueue, communicators, players, games, numberOfThreads);
	}
	
	@Override
	protected void start() {
		listenNewGame();
	}
	
	@Override
	protected void stop() {
		saveGameData();
	}
	
	private void listenNewGame() {
		try {
			DatagramSocket gamePlaySocket = new DatagramSocket(ServerPort.GAME_PLAY.getValue());
			Communicator communicator = new Communicator(gamePlaySocket);
			Command command = communicator.listenCommand();
			
			long hostId = getHostIdFromNewGameCommand(command);
			addCommunicator(hostId, communicator);
			addCommandToQueue(command);
			Log.debug(String.format("Queue adds the command(%s).", command.toString()));
			
		} catch (SocketException socketException) {
			Log.error("If the socket could not be opened, or the socket could not bind to the specified local port.", socketException);
		} catch (IOException ioException) {
			Log.error("If an I/O error occurs.", ioException);
		}
	}
	
	private long getHostIdFromNewGameCommand(Command newGameCommand) {
		if (null == newGameCommand) {
			return 0;
		}
		
		long hostId;
		try {
			hostId = Long.parseLong(newGameCommand.getParameters()[0]);
		} catch (NumberFormatException numberFormatException) {
			Log.error("Parameters must be a long number!");
			return 0;
		}
		return hostId;
	}
	
	private void saveGameData() {
		// TODO Auto-generated method stub
		
	}

}
